/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

 import React, { Component } from 'react';
 import {
   AppRegistry,
   StyleSheet,
   ImageBackground,
   Platform,
   Text,
   View,
   Button,
   FlatList,
   TouchableHighlight,
   Modal
 } from 'react-native';


const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' +
    'Cmd+D or shake for dev menu',
  android: 'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});

export default class Index extends Component<{}> {
  constructor(props){
     super(props);
     this.state = {
       clock: '未初始化',
       list:[],
       modalVisible:false,
       delItem:{}//待删除的项目
     }
   };


   static navigationOptions = {
     title: 'Welcome',
   };

   componentDidMount(){
       let self = this;
       setInterval( () => {
         self.setState({
          clock: new Date().toLocaleTimeString()
        })
        this.getAllList();
      }, 1000)
     
   }
   getAllList = () => {
     
     storage.load({
      key:'dataCords',
      autoSync: false,
      
      // syncInBackground(默认为true)意味着如果数据过期，
      // 在调用sync方法的同时先返回已经过期的数据。
      // 设置为false的话，则等待sync方法提供的最新数据(当然会需要更多时间)。
      syncInBackground: false,
    }).then( ret => {//如果已存在记录，将记录渲染出来
      this.setState({
        list:ret.map( item =>{ return { key:item.time,header:item.header,content:item.content,time:item.time} }) 
      })
    }).catch( err => {//若没记录，显示添加按钮，
      this.setState({
        list:[]
      })
    })
   }
   handleDetail = (index,head) => {//跳任务详情
    const { navigate } = this.props.navigation;
    navigate('listDetail', { index: index,head:head })
   }

   handleDelete = () => {
    let { delItem,list } = this.state;
    let temp = [];
    list.forEach( (item) => {
      if( item.time == delItem.time ){
        '你就是被删除哒'
      }else{
        temp.push(item)
      }
    })
    storage.remove({//总是新数据替换旧数据,这是删掉旧数据，下面是增加新的数据
      key: 'dataCords'
    }).then( () => {
      if( temp.length == 0 ){
        //若没有记录存在则删掉 存储数据的这个数组
      }else{
        storage.save({
          key: 'dataCords',  // 注意:请不要在key中使用_下划线符号!
          data: temp,      
          // 如果不指定过期时间，则会使用defaultExpires参数
          // 如果设为null，则永不过期
          expires: null
        });
      }
    } );
   
    this.setState({
      list:temp
    })
   }

   setModalVisible = (modalVisible) => {//隐藏模态框
      this.setState({modalVisible})
   }
   handleLoadStorage = (suc,fail)=>{
    storage.load({
      key:'dataCords',
      autoSync: false,
      // syncInBackground(默认为true)意味着如果数据过期，
      // 在调用sync方法的同时先返回已经过期的数据。
      // 设置为false的话，则等待sync方法提供的最新数据(当然会需要更多时间)。
      syncInBackground: false,
    }).then( suc(ret)).catch(fail(err))
   }
   render() {
    const { navigate } = this.props.navigation;
     return (
        <ImageBackground source={require('./timg.jpg')} style={styles.container}>
         <View style ={styles.container}>
             <View style ={{ justifyContent: 'center',alignItems: 'center',backgroundColor: 'rgba(0,0,0,0)',flex:2}}>
                { this.state.list.length !== 0 ?  
                  <FlatList
                    data={this.state.list}
                    renderItem={({item}) => {
                      return(
                        <TouchableHighlight onPress={ () => this.handleDetail(item.time,item.header)}
                          onLongPress = { () => {this.setState({modalVisible:true,delItem:item});}}
                        >
                          <Text style={styles.item}>{item.header ? item.header : item.content}</Text>
                        </TouchableHighlight>
                      )
                    }
                  }
                  /> : 
                  <View style={{
                    flex:1,
                    flexDirection:"column",
                    justifyContent:'space-around'
                  }}>
                    <Text style={{color:'#121200'}}> 您当前没有备忘记录，是否添加？ </Text>
                    <Button
                        title="添加"
                        onPress={() => navigate('Detail', { })}
                    />
                  </View>
                }
             </View>
             <Button style={{marginBottom:40,flex:1}}
               title={ this.state.list.length == 0 ? "欢迎使用" : '继续添加'}
               onPress={() =>{
                  if( this.state.list.length == 0 ){
                    alert('suprise')
                  }else{
                    navigate('Detail', { })
                  }
               } }
             />
             <View style = {{alignSelf:"center",flex:1,justifyContent:'center'}}>
               <Text style={{color:'#0c7'}}>
                 {this.state.clock}
               </Text>
             </View>
         </View>
         <View style={{marginTop: 22}}>
          <Modal
            animationType={"slide"}
            transparent={true}
            visible={this.state.modalVisible}
            onRequestClose={() => {alert("Modal has been closed.")}}
            >
          <View style={{flex: 1,backgroundColor:'rgba(0,0,0,.5)'}}>
            <View style={{flex: 1,flexDirection:'column',justifyContent:'center',alignItems:'center'}}>
              <View style={{flex: 1,alignItems:"center",flexDirection:'row',justifyContent:'center'}}>
                <Text style={{ color:'#fff',flex:1,textAlign:'center'}}>确认删除？</Text>
              </View>
              <View style={{ flexDirection:'row',flex:2,alignItems:'center',justifyContent:'center' }}>
                <TouchableHighlight style={{flex:1,backgroundColor:'#ccc',height:40,alignItems:'center',justifyContent:'center'}} onPress={() => {
                  this.setModalVisible(!this.state.modalVisible)
                }}>
                  <Text style={{ color:'#fff',textAlign:'center'}}>取消</Text>
                </TouchableHighlight>
                <TouchableHighlight style={{flex:1,backgroundColor:'green',height:40,justifyContent:'center'}} onPress={() => {
                  this.setModalVisible(!this.state.modalVisible);
                  this.handleDelete();
                }}>
                  <Text style={{ color:'#fff',textAlign:'center'}}>确认</Text>
                </TouchableHighlight>
              </View>
            </View>
          </View>
          </Modal>
          </View>
        </ImageBackground>
       );
     };

}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'rgba(0,0,0,0)',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  item: {
    paddingTop:10,
    fontSize: 14,
    borderBottomWidth:1,
    borderBottomColor:'#333'
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});
